package com.study.recorderbutton.adapter;

import java.util.List;

import com.study.recorderbutton.R;
import com.study.recorderbutton.entities.Recorder;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * listview数据适配器
 * @author Administrator
 *
 */
public class RecorderAdapter extends ArrayAdapter<Recorder> {
	
	private LayoutInflater mInflater;
	
	//item最小宽度
	private int mMinItemWidth;
	//item最大宽度
	private int mMaxItemWidth;

	public RecorderAdapter(Context context, List<Recorder> objects) {
		super(context, -1, objects);
		
		mInflater = LayoutInflater.from(context);
		
		//获取屏幕的大小
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		
		//最大宽度为屏幕宽的百分七十
		mMaxItemWidth = (int) (outMetrics.widthPixels * 0.7f);
		//最小宽度为屏幕宽的百分十五
		mMinItemWidth = (int) (outMetrics.widthPixels * 0.15f);
	}
	
	/**
	 * item数据
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if(convertView == null){
			convertView = mInflater.inflate(R.layout.item_recorder, parent, false);
			holder = new ViewHolder();
			holder.seconds = (TextView) convertView.findViewById(R.id.id_recorder_time);
			holder.length = convertView.findViewById(R.id.id_recorder_length);
			
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		
		//录音时间显示
		holder.seconds.setText(Math.round(getItem(position).getTime())+"\"");
		//设置对话框显示的宽度
		ViewGroup.LayoutParams lp = holder.length.getLayoutParams();
		lp.width = (int) (mMinItemWidth+mMaxItemWidth/60f * getItem(position).getTime());
		return convertView;
	}
	
	/**
	 * 用于listview数据优化
	 * @author Administrator
	 *
	 */
	private class ViewHolder{
		private TextView seconds;
		private View length;
	}

}
